﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Text;



namespace EFRepository
{
    public class RepositoryBase<TMain, TDefaultOrderByType> where TMain : class, IObjectWithChangeTracker, INotifyPropertyChanged
    {
        #region Properties

        public virtual AdnetworkDBEntities Context { get; set; }
        public virtual int Skip { get; set; }
        public virtual int Take { get; set; }
        public virtual bool Asending { get; set; }

        public virtual Expression<Func<TMain, TDefaultOrderByType>> DefaultOrderBy
        {
            get { return null; }
        }

        public virtual ObjectSet<TMain> MainDataSource
        {
            get { return null; }
        }

        private IQueryable<TMain> Query;
        public int Count { get; set; }
        public virtual List<TMain> MainResult { get; set; }

        #endregion

        #region Methods

        #region PrepareParameter

        public virtual void PrepareParameter(int skip, int take, bool asending)
        {
            this.Skip = skip;
            this.Take = take;
            this.Asending = asending;
        }
        #endregion
        #region GetMainDataSource
        public virtual List<TMain> GetMainDataSource<T>(Expression<Func<TMain, T>> orderBy)
        {
            using (Context = new AdnetworkDBEntities())
            {
                DoOrderBy(orderBy);
                DoCount();
                DoResult();
                return MainResult;
            }
        }
        public virtual void DoOrderBy<T>(Expression<Func<TMain, T>> orderBy)
        {
            if (Asending)
            {
                Query = MainDataSource.OrderBy(orderBy).ThenBy(DefaultOrderBy);
            }
            else
            {
                Query = MainDataSource.OrderByDescending(orderBy).ThenBy(DefaultOrderBy);
            }
        }
        public virtual void DoCount()
        {
            Count = Query.Count();
        }
        public virtual void DoResult()
        {
            MainResult = Query.Skip(Skip).Take(Take).ToList();
        }
        #endregion
        #endregion
    }
}
